package com.huatai.exchange.deal;

import com.alibaba.fastjson.JSON;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.FileUtils;
import com.faneui.common.utils.ListUtils;
import com.faneui.dal.DBUtils;
import com.faneui.dbf.utils.DBFUtils;
import com.faneui.service.Dbconfig;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.dal.model.ExcExchangeDateFile;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.FileSourceContents;
import com.huatai.exchange.facade.enums.FileTypeEnum;
import com.huatai.exchange.utils.FileDealUtils;
import com.linuxense.javadbf.DBFField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.sql.Connection;
import java.util.*;

@Service("fileCreateSqlDealService")
public class FileCreateSqlDealServiceImpl extends AbstractFileCreateDealServiceImpl implements FileCreateDealService {

    @Override
    public void downloadCreateFile(StringBuffer fileNames, StringBuffer filePaths, ExcExchangeDateFile exchangeDateFile, ExcDataFileInfo dataFileInfo, Map<String, Object> resvMap) throws BusinessException {
// 参数注入
        Map<String, Object> excDataFileMap = JSON.parseObject(exchangeDateFile.getProperties(), HashMap.class);
        Map<String, Object> valueMap = JSON.parseObject(dataFileInfo.getValue(), HashMap.class);
        String sql = (String) valueMap.get(FileSourceContents.SQL_CONTENT);
        if (StringUtils.isBlank(sql)) {
            String tmpPath = tmpFile + UUID.randomUUID().toString();
            String sqlFilePath = (String) valueMap.get(FileSourceContents.SQL_CONTENT_TXT);
            File tmpFile = new File(tmpPath);
            fileOperateService.downloadFile(tmpFile, sqlFilePath);
            sql = FileUtils.readFile(tmpFile);
            tmpFile.deleteOnExit();
            logger.info("读取文件：" + sql);
        }
        sql = FileDealUtils.formatStr(sql, excDataFileMap, resvMap);
        String jdbcUrl = (String) valueMap.get(FileSourceContents.SQL_JDBC_URL);
        String jdbcUser = (String) valueMap.get(FileSourceContents.SQL_JDBC_USER);
        String jdbcPassword = (String) valueMap.get(FileSourceContents.SQL_JDBC_PASSWORD);
        if (StringUtils.isBlank(jdbcPassword)) {
            jdbcPassword = Dbconfig.getPasswordByUserId(jdbcUser);
        }
        String fileType = (String) valueMap.get(FileSourceContents.FILE_TYPE);
        String fileTemplate = (String) valueMap.get(FileSourceContents.FILE_TEMPLATE);
        String fileName = FileDealUtils.formatStr(dataFileInfo.getFileName(), excDataFileMap, resvMap);
        String tmpFilePath = tmpFile + UUID.randomUUID().toString();
        Connection conn = null;
        try {
            conn = DBUtils.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
            List<Map<String, Object>> result = DBUtils.executeQuery(conn, sql);
            if (FileTypeEnum.DBF.toString().equals(fileType)) {
                // 无数据 处理逻辑
                if (ListUtils.isEmpty(result)) {
                    // 需要空文件 则将模板文件复制过去
                    if (!Contents.boolean_true.equals(exchangeDateFile.getIsAllowEmpty())) {
                        if (Contents.boolean_true.equals(dataFileInfo.getMoreFlag())) {
                            String s = FileDealUtils.formatStr((String) valueMap.get(FileSourceContents.SQL_NULL_DATA_CONTENT), excDataFileMap, resvMap);
                            if (StringUtils.isBlank(s)) {
                                throw new BusinessException("请配置空数据是文件名SQL[SQL_NULL_DATA_CONTENT]");
                            }
                            List<Map<String, Object>> r = DBUtils.executeQuery(conn, s);
                            if (ListUtils.isEmpty(r)) {
                                return;
                            }
                            String field = FileDealUtils.getFirstField(fileName);
                            for (Map<String, Object> map : r) {
                                String value = map.get(FileSourceContents.SQL_NULL_DATA_FIELD) + "";
                                String mxFileName = FileDealUtils.formatStr(fileName.replace("${" + field + "}", value), excDataFileMap, resvMap);
                                fileNames.append(",").append(mxFileName);
                                filePaths.append(",").append(fileTemplate);
                            }
                        } else {
                            // 如果数据是空，是多文件的话
                            filePaths.append(",").append(fileTemplate);
                            fileNames.append(",").append(fileName);
                        }
                    }
                    // 不需要空文件，则退出
                } else {
                    // 有数据时的处理方式
                    String templateFilePath = tmpFile + UUID.randomUUID().toString();
                    fileOperateService.downloadFile(new File(templateFilePath), fileTemplate);
                    DBFField[] dbfFields = DBFUtils.getDBFields(templateFilePath);
                    // 如果 不是多个文件 ，数据就插入
                    if (!Contents.boolean_true.equals(dataFileInfo.getMoreFlag())) {
                        FileDealUtils.createDBFFile(dbfFields, tmpFilePath, result);
                        String filePath = fileOperateService.uploadFile(new File(tmpFilePath));
                        filePaths.append(",").append(filePath);
                        fileNames.append(",").append(fileName);
                    } else {
                        String field = FileDealUtils.getFirstField(fileName);
                        Map<String, List<Map<String, Object>>> dataListMap = FileDealUtils.convert(result, field);
                        Set<String> keySet = dataListMap.keySet();
                        for (String key : keySet) {
                            logger.info("key:" + key + ",field:" + field);
                            String mxFileName = FileDealUtils.formatStr(fileName.replace("${" + field + "}", key), excDataFileMap, resvMap);
                            String mxTmpFilePath = tmpFile + (UUID.randomUUID().toString());
                            FileDealUtils.createDBFFile(dbfFields, mxTmpFilePath, dataListMap.get(key));
                            fileNames.append(",").append(mxFileName);
                            String filePath = fileOperateService.uploadFile(new File(mxTmpFilePath));
                            filePaths.append(",").append(filePath);
                            new File(mxTmpFilePath).deleteOnExit();
                        }

                        // 再根据
                        String s = FileDealUtils.formatStr((String) valueMap.get(FileSourceContents.SQL_NULL_DATA_CONTENT), excDataFileMap, resvMap);
                        if (StringUtils.isNotBlank(s)) {
                            List<Map<String, Object>> r = DBUtils.executeQuery(conn, s);
                            if (ListUtils.isNotEmpty(r)) {
                                for (Map<String, Object> map : r) {
                                    String value = map.get(FileSourceContents.SQL_NULL_DATA_FIELD) + "";
                                    String mxFileName = FileDealUtils.formatStr(fileName.replace("${" + field + "}", value), excDataFileMap, resvMap);
                                    if (!fileNames.toString().contains(mxFileName)) {
                                        fileNames.append(",").append(mxFileName);
                                        filePaths.append(",").append(fileTemplate);
                                    }
                                }
                            }

                        }

                    }
                }
            }
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            DBUtils.closeAll(conn);
        }
    }
}
